/**
 * 工程款计算工具函数
 * 确保所有页面的计算逻辑保持一致
 */

/**
 * 计算工程的未结清金额
 * @param {Object} project 工程对象
 * @returns {number} 未结清金额
 */
export function calculateUnpaidAmount(project) {
	if (project.status === 'paid') {
		return 0
	}
	
	if (project.status === 'unpaid') {
		return project.totalAmount || 0
	}
	
	if (project.status === 'partial') {
		// 计算已付款总额
		const payments = uni.getStorageSync('project_payments') || []
		const projectPayments = payments.filter(p => p.projectId === project.id)
		const totalPaid = projectPayments.reduce((paidSum, p) => paidSum + p.amount, 0)
		// 返回剩余未付金额
		return Math.max(0, (project.totalAmount || 0) - totalPaid)
	}
	
	return project.totalAmount || 0
}

/**
 * 计算工程的已付款金额
 * @param {Object} project 工程对象
 * @returns {number} 已付款金额
 */
export function calculatePaidAmount(project) {
	if (project.status === 'paid') {
		return project.totalAmount || 0
	}
	
	if (project.status === 'partial') {
		// 计算已付款总额
		const payments = uni.getStorageSync('project_payments') || []
		const projectPayments = payments.filter(p => p.projectId === project.id)
		return projectPayments.reduce((paidSum, p) => paidSum + p.amount, 0)
	}
	
	return 0
}

/**
 * 计算工程列表的总未结清金额
 * @param {Array} projects 工程列表
 * @returns {number} 总未结清金额
 */
export function calculateTotalUnpaidAmount(projects) {
	return projects.reduce((sum, project) => {
		return sum + calculateUnpaidAmount(project)
	}, 0)
}

/**
 * 计算工程列表的总已付款金额
 * @param {Array} projects 工程列表
 * @returns {number} 总已付款金额
 */
export function calculateTotalPaidAmount(projects) {
	return projects.reduce((sum, project) => {
		return sum + calculatePaidAmount(project)
	}, 0)
}

/**
 * 计算工程列表的总工程款
 * @param {Array} projects 工程列表
 * @returns {number} 总工程款
 */
export function calculateTotalAmount(projects) {
	return projects.reduce((sum, project) => {
		return sum + (project.totalAmount || 0)
	}, 0)
}

/**
 * 获取工程状态文本
 * @param {string} status 状态
 * @returns {string} 状态文本
 */
export function getStatusText(status) {
	const statusMap = {
		'unpaid': '未付款',
		'partial': '部分付款',
		'paid': '已结清'
	}
	return statusMap[status] || '未知'
}
